package com.GatherFour;

import game.ghostleg.GhostLegAPI14newActivity;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class GameLobby extends Activity {
	private Button send_btn, start_btn;
	private EditText edText;
	private TextView chatbox; 
	private TextView[] playerName = new TextView[4];
	private Player user;
	private String address;
	private Socket outSocket, client;
	private ServerSocket inSocket;
	private String inMessage, outMessage;
	private Intent intent;
	protected Context context;
	private boolean firstTimeFlag = true; 
	private int playerNum;
	private String[] clientList;
	private int[] clientScores;
	private boolean ready = false;
	private Class game = game.MazeRunner.MazeRunnerActivity.class;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.game_lobby);
		context = this.getApplicationContext();
		
		send_btn = (Button)findViewById(R.id.sendText);
		edText = (EditText)findViewById(R.id.inputText);
		playerName[0] = (TextView)findViewById(R.id.player1);
		playerName[1] = (TextView)findViewById(R.id.player2);
		playerName[2] = (TextView)findViewById(R.id.player3);
		playerName[3] = (TextView)findViewById(R.id.player4);
		chatbox = (TextView)findViewById(R.id.chatbox);
		chatbox.setText("");
		//game = MazeRunnerActivity.class;
		
		Bundle bundle = this.getIntent().getExtras();
		
		if(bundle.getString("self").equals("host")){
			user = new Player(bundle.getString("name"));
			user.setHostPlayer();
			user.playerID = 0;
			playerNum = bundle.getInt("clientNum")+1;
			clientList = bundle.getString("clientList").split("\\|");
			clientScores = new int[playerNum];
			for(int i = 0; i< playerNum; i++)
				clientScores[i] = 100;
			System.err.println(bundle.getString("clientList"));
			address = bundle.getString("address");
			playerName[0].setText(user.name);
			for(int j = 0; j< playerNum-1; j++){
				playerName[j+1].setText(clientList[j]);
			}

			
			setupHostSocket();
			hostInit();
			
			
			
		}else{
			user = new Player(bundle.getString("name"));
			user.setClientPlayer();
			user.playerID = 1;
			
			address = bundle.getString("address");

			setupClientSocket();
			clientInit();
		}
		
	//	manager.createGroup(channel, null);
		//Start Game Button
		start_btn = (Button)this.findViewById(R.id.startGameID);
		if(user.isHostPlayer()){
			//start_btn = (Button)this.findViewById(R.id.startGameID);
			
			start_btn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(ready == true){
						sendShortMsg(address, 9001, "0000gameStart");
						
						intent = new Intent(context,game);
						String[] c_address = new String[4];
						for(int i = 0 ; i < 4; i++){
							c_address[i] = address;
						}
						
						Bundle bundle = new Bundle();
						bundle.putString("name", user.name);
						bundle.putInt("score", user.score);
						bundle.putString("self", "host");
						bundle.putStringArray("clientAddr", c_address);
						intent.putExtras(bundle);
						startActivityForResult(intent, 0);
					}
				}
				
			});
		}else{
			start_btn.setText("Ready");
			
			start_btn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					sendShortMsg(address, 9000, "0000gameReady");
					if(ready != true){
						ready = true;		
						playerName[user.playerID].setText(user.name+": Ready");
						start_btn.setText("Cancel");
						
					}else{
						ready = false;
						playerName[user.playerID].setText(user.name+": Canceled");
						start_btn.setText("Ready");
						
					}
				}
					
				
			});
		}
		
	}
	
	public void hostInit(){
		send_btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				outMessage = edText.getText().toString();
				chatbox.append("\n"+outMessage);
				
				edText.setText("");
				
				sendShortMsg(address, 9001, outMessage);
				
			}
			
		});
		
		sendShortMsg(address, 9001, getNameList());

	}
	
	public void clientInit(){
		send_btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				outMessage = edText.getText().toString();
				chatbox.append("\n"+outMessage);
				
				edText.setText("");
				
				sendShortMsg(address, 9000, outMessage);
				
			}
			
		});

	}
	
	public void setupHostSocket(){
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					inSocket = new ServerSocket(9000);
					while(true){
						client = inSocket.accept();
						Scanner in = new Scanner(client.getInputStream());
						if(in.hasNextLine()){
							inMessage = in.nextLine();
							
							if(inMessage.equals("scoreReport")){
								String[] tempstr = in.nextLine().split(":");
								clientScores[Integer.valueOf(tempstr[0])] = Integer.valueOf(tempstr[1]);
								runOnUiThread(updateScore);
							}else if(inMessage.equals("0000gameReady")){
								if(ready == false){
									ready = true;
									//playerName[1].setText(clientList[0]+": Ready");
								}else {
									ready = false;
									//playerName[1].setText(clientList[0]+": Canceled");
								}
							}else {
								runOnUiThread(updateChatbox);
							}
							
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}).start();
	}
	
	public void setupClientSocket(){
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					if(firstTimeFlag){
						inSocket = new ServerSocket(9001);
						firstTimeFlag = false;
					}
					while(true){
						client = inSocket.accept();
						Scanner in = new Scanner(client.getInputStream());
						if(in.hasNextLine()){
							inMessage = in.nextLine();
							if(inMessage.equals("nameList")){
								final String[] nameList = in.nextLine().split("\\|");
								System.err.println("NAMELIST"+nameList.length);
								runOnUiThread(new Runnable(){

									@Override
									public void run() {
										// TODO Auto-generated method stub
										for(int i = 0; i< nameList.length; i++){
											playerName[i].setText(nameList[i]);
										}
									}
									
								});
							}else if(inMessage.equals("updateScore")){
								final String[] nameWithScores = in.nextLine().split("\\|");
								runOnUiThread(new Runnable(){

									@Override
									public void run() {
										// TODO Auto-generated method stub
										for(int i = 0; i< nameWithScores.length; i++){
											playerName[i].setText(nameWithScores[i]);
										}
									}
									
								});
								
							}else if(inMessage.equals("0000gameStart")){
								
								intent = new Intent(context,game);
								
								Bundle bundle = new Bundle();
								bundle.putString("name", user.name);
								bundle.putInt("score", user.score);
								bundle.putString("self", "client");
								bundle.putString("hostAddr", address);
								intent.putExtras(bundle);
								startActivityForResult(intent,0);
								
							}else{
								runOnUiThread(updateChatbox);
							}
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}).start();
	}
	
	public Runnable updateChatbox = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			chatbox.append("\n"+inMessage);
		}
		
	};
	
	public Runnable updateScore = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(user.isHostPlayer()){
				for(int i = 0; i< playerNum; i++){
					if(i == 0)
						playerName[i].setText(user.name+": "+user.score);
					else
						playerName[i].setText(clientList[i-1]+": "+clientScores[i]);
				}
				
				String msg = "updateScore\n"+user.name+": "+user.score+"|";
				
				for(int i = 0; i< playerNum-1; i++){
					if(i == playerNum-2)
						msg = msg+clientList[i]+": "+clientScores[i+1];
					else
						msg = msg+clientList[i]+": "+clientScores[i+1]+"|";
				}
				
				sendShortMsg(address, 9001, msg);
				
				
				
			}
		}
		
	};
	
	public String getNameList(){
		String result = "nameList\n"+user.name;
		for(int i = 0; i< playerNum-1 ; i++){
			result = result+"|"+clientList[i];
		}
			
		return result;
	}
	
	public void sendShortMsg(final String addr, final int port, final String msg){
		new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					outSocket = new Socket(addr,port);
					OutputStream out = outSocket.getOutputStream();
					out.write(msg.getBytes());
					outSocket.close();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	/*
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case 0:
			Bundle b=data.getExtras(); 
			final int score=b.getInt("score"+user.playerID);
            
			new Thread(new Runnable(){

				@Override
				public void run() {
				try {
					if(user.isHostPlayer()){
						user.score = score;
					}else{
						outSocket = new Socket(address,9000);
						OutputStream out = outSocket.getOutputStream();
						String initMsg = "scoreReport\n"+user.playerID+":"+score ;
						out.write(initMsg.getBytes());
						outSocket.close();
					}
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			}).start();
			
			break;
                      
		default:
	           break;
		}
	}
	*/
}
